package com.tutsnnd.personnl_information_display_system.controller;

import com.tutsnnd.personnl_information_display_system.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${image.path}")
    private String basspath;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String sufixx = originalFilename.toString().substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + sufixx;
        File dirs = new File(basspath);
        if (!dirs.exists()){
            dirs.mkdir();
        }

        try {
            file.transferTo(new File(basspath+filename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return R.success(filename);
    }
    @GetMapping("/download")
    public void download(String name , HttpServletResponse response){
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basspath+name));
            ServletOutputStream servletOutputStream = response.getOutputStream();
            int len=0;
            byte[] bytes=new byte[1024];
            while ((len=fileInputStream.read(bytes))!=-1){
                servletOutputStream.write(bytes,0,len);
                servletOutputStream.flush();

            }
            fileInputStream.close();
            servletOutputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}
